
import UIKit

public enum TriangleDirection {
    case top, left, bottom, right
}

public class TriangleView : UIView {
    
    public var background: UIColor? {
        didSet {
            setNeedsDisplay()
        }
    }
    public var borderColor: UIColor?
    public var borderWidth: CGFloat?
    public var direction: TriangleDirection = .top
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override public func draw(_ rect: CGRect) {
        
        guard let context = UIGraphicsGetCurrentContext() else { return }
        context.saveGState()
        context.beginPath()
        
        var point1: CGPoint, point2: CGPoint, point3: CGPoint
        
        switch direction {
        case .top:
            point1 = CGPoint(x: rect.minX, y: rect.maxY)
            point2 = CGPoint(x: rect.maxX, y: rect.maxY)
            point3 = CGPoint(x: (rect.maxX / 2.0), y: rect.minY)
        case .left:
            point1 = CGPoint(x: rect.minX, y: (rect.maxY / 2.0))
            point2 = CGPoint(x: rect.maxX, y: rect.maxY)
            point3 = CGPoint(x: rect.maxX, y: rect.minY)
        case .bottom:
            point1 = CGPoint(x: rect.minX, y: rect.minY)
            point2 = CGPoint(x: (rect.maxX / 2.0), y: rect.maxY)
            point3 = CGPoint(x: rect.maxX, y: rect.minY)
        case .right:
            point1 = CGPoint(x: rect.minX, y: rect.maxY)
            point2 = CGPoint(x: rect.minX, y: rect.minY)
            point3 = CGPoint(x: rect.maxX, y: (rect.maxY / 2.0))
        }
        
        
        // draw triangle
        
        context.move(to: point1)
        context.addLine(to: point2)
        context.addLine(to: point3)

        if let color = background {
            context.setFillColor(color.cgColor)
        } else {
            context.setFillColor(red: 0.9, green: 0.1, blue: 0.1, alpha: 0.90)
        }
        
        context.closePath()
        context.fillPath()
        
        
        // draw border
        
        context.move(to: point1)
        context.addLine(to: point2)
        context.move(to: point3)
        context.addLine(to: point1)
        
        if let color = borderColor {
            context.setStrokeColor(color.cgColor)
        } else {
            context.setStrokeColor(red: 1.0, green: 1, blue: 1, alpha: 0.60)
        }
        
        if let width = borderWidth {
            context.setLineWidth(width)
        } else {
            context.setLineWidth(0.5)
        }
        context.strokePath()
        
        context.restoreGState()
    }
}


